package org.example.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 消费者
 */
public class CustomConsumerAutoOffset {
    public static void main(String[] args) {
        // 配置
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.211.55.104:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

        // 组id
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test");

        // 自定提交
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, true);
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 1000); // 提交时间间隔

        // 创建一个消费者
        try (KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(properties)) {

            // 订阅 first 主题
            List<String> topics = new ArrayList<>();
            topics.add("first");
            kafkaConsumer.subscribe(topics);

            //  消费数据
            while (true) {
                ConsumerRecords<String, String> poll = kafkaConsumer.poll(Duration.ofSeconds(1));
                for (ConsumerRecord<String, String> consumerRecord : poll) {
                    System.out.println(consumerRecord);
                }

            }

        }
    }
}

